<template>
  <fieldset>
    <legend>三级联动</legend>
    省:
    <select v-model="sel1" @change="provienceChange(sel1)">
      <option :value="item.id" v-for="item in provience" :key="item.id">
        {{ item.name }}
      </option>
    </select>
    市:
    <select v-model="sel2" @change="cityChange(sel2)">
      <option v-for="item in citys" :key="item.id" :value="item.id">
        {{ item.name }}
      </option>
    </select>
    县:
    <select v-model="sel3">
      <option v-for="item in county" :key="item.id" :value="item.id">
        {{ item.name }}
      </option>
    </select>
  </fieldset>
</template>

<script>
import * as api from "@/api/select";

export default {
  data() {
    return {
      //存储省的数据
      provience: [],
      sel1: 1,
      //存储市的数据
      citys: [],
      sel2: "",
      //存储县的数据
      county: [],
      sel3: "",
    };
  },
  mounted() {
    api.fetchData().then((res) => {
      console.log("res1==", res);
      //获取所有省的数据
      // let data = res.data.data;
      // this.provience = data.filter(item => item.parentId === 0)
      this.provience = res;
      //获取默认第一条的id
      let pid = res[0].id;
      this.provienceChange(pid);
    });
  },
  methods: {
    //选择的省变化的时候，获取所选的省对应的id，并请求市的数据
    provienceChange(pid) {
      api.fetchCity(pid).then((res) => {
        console.log("res2==", res);
        this.citys = res;
        this.sel2 = res[0].id;
        let cid = res[0].id;
        this.cityChange(cid);
      });
    },
    cityChange(cid) {
      api.fetchCounty(cid).then((res) => {
        console.log("res3==", res);
        this.county = res;
        //默认选中
        this.sel3 = res[0].id;
      });
    },
  },
};
</script>

<style>
select {
  width: 100px;
}
</style>
